package cn.txy.course.controller;

import cn.txy.config.R;
import cn.txy.course.domain.Course;
import cn.txy.course.query.CourseQuery;
import cn.txy.course.service.CourseService;
import cn.txy.system.annotation.PreAuthorize;
import cn.txy.util.ExcelUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/course")
public class CourseController {
    @Autowired
    private CourseService courseService;

    @GetMapping("/{id}")
    @PreAuthorize(name = "根据ID查询课程",sn="course:getOne",descs = "根据ID查询课程")
    public R findById(@PathVariable("id")Long id){
        return R.ok(courseService.findById(id));
    }

    @GetMapping
    @PreAuthorize(name = "查询课程",sn="course:getAll",descs = "查询课程")
    public R findAll(){
        return R.ok(courseService.findAll());
    }

    @DeleteMapping("/{id}")
    @PreAuthorize(name = "根据ID删除课程",sn="course:delOne",descs = "根据ID删除课程")
    public R deleteById(@PathVariable("id")Long id){
        courseService.deleteById(id);
        return R.ok();
    }
    @PostMapping("/deleteAll")
    @PreAuthorize(name = "删除课程",sn="course:delAll",descs = "删除课程")
    public R batchDelete(@RequestBody List<Long> ids){
        courseService.batchDelete(ids);
        return R.ok();
    }

    @ApiOperation("添加和修改")
    @PostMapping
    @PreAuthorize(name = "添加和修改课程",sn="course:saveOne",descs = "添加和修改课程")
    public R add(@RequestBody Course course){
        if(course.getId() == null){
            courseService.add(course);
        }else {
            courseService.update(course);
        }
        return R.ok();
    }
    @PostMapping("/page")
    @PreAuthorize(name = "分页查询课程",sn="course:page",descs = "分页查询课程")
    public R getPage(@RequestBody CourseQuery courseQuery){
        PageHelper.startPage(courseQuery.getPage(),courseQuery.getSize());
        List<Course> courses = courseService.queryPage(courseQuery);
        PageInfo<Course> pageInfo = new PageInfo<>(courses);
        return R.ok(pageInfo);
    }
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        List<Course> list = courseService.findAll();
        ExcelUtil.exportExcel(list, "课程表", "课程表", Course.class, "courses", response);
    }

}
